package com.gu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.exception.DiyException;
import com.gu.entity.*;
import com.gu.entity.vo.CourseInfoVo;
import com.gu.entity.vo.CoursePublishVo;
import com.gu.entity.vo.CourseQuery;
import com.gu.entity.vo.front.ChapterFrontVo;
import com.gu.entity.vo.front.CourseDetailVo;
import com.gu.entity.vo.front.CourseFrontVo;
import com.gu.service.*;
import com.gu.mapper.EduCourseMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse>
        implements EduCourseService {

    @Resource
    private EduCourseDescriptionService eduCourseDescriptionService;

    @Resource
    private EduVideoService eduVideoService;

    @Resource
    private EduTeacherService eduTeacherService ;

    @Resource
    private EduChapterService eduChapterService;

    @Resource
    private OssClients ossClients;

    //分页条件查询：(默认按照添加的时间进行降序排列)
    @Override
    @Transactional
    public Page<EduCourse> getCourseListPage(CourseQuery courseQuery, Long current, Long limit) {
        if (current < 0 || limit < 0) {
            throw new DiyException("444", "分页数据不能为负数");
        }
        QueryWrapper<EduCourse> courseWrapper = new QueryWrapper<>();
        Page<EduCourse> coursePage = new Page<>(current, limit);

        if (!StringUtils.isEmpty(courseQuery.getTitle()) && StringUtils.isEmpty(courseQuery.getStatus())) {
            courseWrapper.like("title", courseQuery.getTitle());

        } else if (!StringUtils.isEmpty(courseQuery.getTitle()) && !StringUtils.isEmpty(courseQuery.getStatus())) {
            courseWrapper.like("title", courseQuery.getTitle()).eq("status", courseQuery.getStatus());
        }
        Page<EduCourse> pageParams = this.page(coursePage, courseWrapper);
        return pageParams;
    }

    //根据course删除对应课程：


    @Override
    @Transactional
    public boolean deleteCourseById(String courseId) {
        //1.从小到大依次删除，先查后改：
        EduCourse eduCourse = this.getById(courseId);
        String coverUrl = eduCourse.getCover();

        if (!StringUtils.isEmpty(coverUrl)) {
            //调用微服务 oss模块
            String coverName = coverUrl.substring(coverUrl.indexOf("202"));
            ossClients.deleteByUrl(coverName);
        }
        boolean result1 = eduVideoService.removeByCourseId(courseId);
        boolean result2 = eduChapterService.removeByCourseId(courseId);
        boolean result3 = eduCourseDescriptionService.removeByCourseId(courseId);
        boolean result4 = this.removeById(courseId);
        boolean result = result1 && result2 && result3 && result4;
        return true;
    }

    //按照课程ID查询
    @Override
    public CourseInfoVo getCourseById(String courseId) {

        EduCourse eduCourse = this.getById(courseId);
        String description = eduCourseDescriptionService.getById(courseId).getDescription();

        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse, courseInfoVo);
        courseInfoVo.setDescription(description);
        return courseInfoVo;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    //urd 则用 require ，c则用support 默认是抛出 了RuntimeException 就会进行捕获 回滚
    public String saveOrUpdateCourse(CourseInfoVo courseInfoVo) {
        //1.先查后判断是否需要修改，用于回显
        String courseId = courseInfoVo.getId();
        if (this.getById(courseId) == null) {

            EduCourse eduCourse = new EduCourse();
            BeanUtils.copyProperties(courseInfoVo, eduCourse);
            Boolean result = this.save(eduCourse);
            courseId = eduCourse.getId();
            if (result) {
                //添加课程评论,课程主键和 课程评论的主键 一致
                EduCourseDescription eduCourseDescription = new EduCourseDescription();
                BeanUtils.copyProperties(courseInfoVo, eduCourseDescription);
                eduCourseDescription.setId(eduCourse.getId());

                result = eduCourseDescriptionService.save(eduCourseDescription);
            }
        } else {
            //此处不等于空，回显后 跟新数据库中数据
            QueryWrapper<EduCourse> courseWrapper = new QueryWrapper<>();
            EduCourse eduCourse = new EduCourse();
            courseWrapper.eq("id", courseId);
            BeanUtils.copyProperties(courseInfoVo, eduCourse);
            boolean result = this.updateById(eduCourse);
            if (result) {
                EduCourseDescription eduCourseDescription = new EduCourseDescription();
                BeanUtils.copyProperties(courseInfoVo, eduCourseDescription);
                eduCourseDescription.setId(eduCourse.getId());
                QueryWrapper<EduCourseDescription> desWrapper = new QueryWrapper<>();
                desWrapper.eq("id", courseId);

                result = eduCourseDescriptionService.updateById(eduCourseDescription);
            }
        }
        return courseId;
    }

    //获取最终发布 的确认信息：
    @Override
    public CoursePublishVo getCoursePublishInfoById(String courseId) {

        CoursePublishVo coursePublishInfo = baseMapper.getCoursePublishInfo(courseId);
        return coursePublishInfo;
    }

    /**
     * 此处区域 属于 前台控件区域：
     */

    @Override
    public Page<EduCourse> getCourseForIndex() {
        //显示级别较高的 老师：
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        Page<EduCourse> coursePage = new Page<>(1, 4);
        wrapper.orderByDesc("buy_count");
        Page<EduCourse> Page = this.page(coursePage, wrapper);
        return Page;
    }


    /**
     * 前台接口区域
     */
    @Override
    public Page<EduCourse> getCourseListFront(String current, CourseFrontVo courseFrontVo) {
        QueryWrapper<EduCourse> eduCourseQueryWrapper = new QueryWrapper<>();
        long currentPage = Long.parseLong(current);
        Page<EduCourse> coursePage = new Page<EduCourse>(currentPage, 4);

        String subjectParentId = courseFrontVo.getSubjectParentId();
        String subjectId = courseFrontVo.getSubjectId();
        String courseQuery = courseFrontVo.getCourseQuery();

        if (!StringUtils.isEmpty(courseQuery) && courseQuery.equals("price")) {
            eduCourseQueryWrapper.orderByAsc("price");
        }
        if (!StringUtils.isEmpty(courseQuery) && courseQuery.equals("gmt_create")) {
            eduCourseQueryWrapper.orderByDesc("gmt_create");
        }
        if (!StringUtils.isEmpty(courseQuery) && courseQuery.equals("view_count")) {
            eduCourseQueryWrapper.orderByDesc("view_count");
        }
        if(!StringUtils.isEmpty(subjectParentId)){
            eduCourseQueryWrapper.eq("subject_parent_id",subjectParentId);
        }
        if(!StringUtils.isEmpty(subjectId)){
            eduCourseQueryWrapper.eq("subject_id",subjectId);
        }
        Page<EduCourse> page = this.page(coursePage, eduCourseQueryWrapper);
        return page ;
    }

    //前台获取课程详情方法：
    @Override
    public CourseDetailVo getCourseDetailById(String courseId) {
        //查课程
        EduCourse course = this.getById(courseId);
        //查教师
        String teacherId = course.getTeacherId();
        EduTeacher teacher = eduTeacherService.getById(teacherId);
        //查章节
        List<ChapterFrontVo> chapterFrontVoList = new ArrayList<>();

        QueryWrapper<EduChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id",courseId);
        List<EduChapter> chapterList = eduChapterService.list(chapterQueryWrapper);

        chapterList.forEach(chapter -> {
            ChapterFrontVo chapterFrontVo = new ChapterFrontVo();
            QueryWrapper<EduVideo> videoQueryWrapper = new QueryWrapper<>();
            videoQueryWrapper.eq("chapter_id",chapter.getId());
            List<EduVideo> videoList = eduVideoService.list(videoQueryWrapper);
            chapterFrontVo.setId(chapter.getId());
            chapterFrontVo.setTitle(chapter.getTitle());
            chapterFrontVo.setVideoList(videoList);
            chapterFrontVoList.add(chapterFrontVo);
        });

        //查询课程描述
        EduCourseDescription description = eduCourseDescriptionService.getById(courseId);

        CourseDetailVo courseDetailVo = new CourseDetailVo();
        BeanUtils.copyProperties(course,courseDetailVo);
        BeanUtils.copyProperties(teacher,courseDetailVo);
        BeanUtils.copyProperties(description,courseDetailVo);

        courseDetailVo.setChapterList(chapterFrontVoList);
        return courseDetailVo;
    }
}




